'use strict'

const rp = require('request-promise')
const _ = require('underscore')
const Promise = require('bluebird')

const host = 'https://birdie2.wilddogio.com'

module.exports = {

  getInvitees (roomId) {
    const url = `${host}/matchRoom/${roomId}/invitees.json`
    return rp(url)
  },

  getMatchRoomMembers (roomId) {
    var url = `${host}/matchRoom/${roomId}/members.json`
    return rp(url)
  },

  joinRoom (roomId, userObjId) {
    return this.getInvitees(roomId).then((ret) => {
      console.log('invi', ret)
      if (!ret) return Promise.reject({errMsg: 'not been invited'})
      var arr = _.map(JSON.parse(ret), x => x)
      console.log(arr)
      if (arr.indexOf(userObjId) === -1) return Promise.reject({errMsg: 'not been invited'})
      return this.getMatchRoomMembers(roomId)
    }).then(ret => {
      console.log(ret)
      const uri = `${host}/matchRoom/${roomId}/members.json`
      ret = _.map(JSON.parse(ret), x => x)
      if (ret.indexOf(userObjId) !== -1) return Promise.resolve({state: 'has joined'})
      ret.push(userObjId)
      return rp({
        uri,
        method: 'PUT',
        body: JSON.stringify(ret)
      })
    })
  }


}
